
import traceback
from jsonschema import ValidationError
from jwt import ExpiredSignatureError
from sanic import Sanic, json, text
from app.core.entity import ApiResult
from loguru import logger


class ApiException(Exception):
    code = 1
    msg = "失败"
    def __init__(self, *args: object,code=1) -> None:
        super().__init__(*args)
        self.code = code
        self.msg = args[0]

def initException(app:Sanic):
    from app.core.modal import Modal
    from sqlalchemy.exc import SQLAlchemyError

    @app.exception(ApiException)
    def apiExceptionResponse(request,exception:ApiException):
        logger.error(str(exception)+"\n"+traceback.format_exc())
        return json(ApiResult.error(msg=exception.args[0],code=exception.code).toDict())
    
    @app.exception(ValidationError)
    def ValidationErrorResponse(request,exception:ValidationError):
        logger.error(str(exception)+"\n"+traceback.format_exc())
        return json(ApiResult.error(msg=exception.message).toDict())
    
    @app.exception(ExpiredSignatureError)
    def ExpiredSignatureErrorResponse(request,exception:Exception):
        logger.error(str(exception)+"\n"+traceback.format_exc())
        return json(ApiResult.error(msg=str(exception),code=3).toDict())

    @app.exception(Exception)
    def NormalErrorResponse(request,exception:Exception):
        logger.error(str(exception)+"\n"+traceback.format_exc())
        return json(ApiResult.error(msg=str(exception)).toDict())
        
    